// ==================== 交互服务 ====================
// 职责：处理用户交互相关的逻辑
// 实现酷家乐式的交互体验

import { ref } from 'vue'
import { usePlacementStore, useLayerStore, useHistoryStore } from '@/stores'

export function useInteraction(canvasService, triggerRedraw) {
  const placementStore = usePlacementStore()
  const layerStore = useLayerStore()
  const historyStore = useHistoryStore()
  
  // ==================== 交互状态 ====================
  const mousePosition = ref({ x: 0, y: 0 })   // 鼠标位置（世界坐标）
  const isDragging = ref(false)               // 是否正在拖拽
  const dragStart = ref({ x: 0, y: 0 })       // 拖拽开始位置
  const dragType = ref('')                    // 拖拽类型：'view' | 'object' | 'selection' | 'resize' | 'rotation'
  const resizeControlPoint = ref('')          // 缩放控制点类型
  const resizeObject = ref(null)              // 正在缩放的对象
  const rotationObject = ref(null)            // 正在旋转的对象
  const rotationStartAngle = ref(0)           // 开始旋转时的对象角度

  // ==================== 交互处理函数 ====================
  /**
   * 处理鼠标按下事件
   * 酷家乐式交互：
   * - 左键点击对象：选择对象
   * - 左键拖拽空白区域：平移视图
   * - 左键拖拽对象：移动对象
   * - 中键拖拽：平移视图
   */
  const handleMouseDown = (event) => {
    const rect = canvasService.canvasRef.value.getBoundingClientRect()
    
    const screenX = event.clientX - rect.left
    const screenY = event.clientY - rect.top
    const worldPos = canvasService.screenToWorld(screenX, screenY) // 拿到真实的世界坐标
    
    
    mousePosition.value = worldPos
    
    if (event.button === 0) { // 左键
      // 放置模式：点击确认落位到家具层，然后进入对象拖拽
      if (placementStore.isPlacing && placementStore.item) {
        const world = worldPos
        const newObj = {
          id: Date.now().toString(36) + Math.random().toString(36).slice(2),
          type: 'image',
          name: placementStore.item.name,
          x: world.x - placementStore.size.width / 2,
          y: world.y - placementStore.size.height / 2,
          width: placementStore.size.width,
          height: placementStore.size.height,
          rotation: 0,
          zIndex: 10,
          layerId: 'furniture',
          image: placementStore.image || null,
          imageUrl: placementStore.item.thumbnail
        }
        layerStore.addObjectToLayer('furniture', newObj)
        // 写入历史：创建对象
        historyStore.addHistoryItem({
          type: 'object_create',
          action: 'create',
          data: {
            object: { ...newObj }
          },
          description: `放置素材：${newObj.name}`
        })
        
        // 选中并进入拖拽
        canvasService.handleObjectSelection(newObj, false)
        isDragging.value = true
        dragType.value = 'object'
        dragStart.value = { x: worldPos.x, y: worldPos.y }
        // 记录初始位置用于撤销
        newObj.__history = { start: { x: newObj.x, y: newObj.y }, startSize: { width: newObj.width, height: newObj.height }, startRotation: newObj.rotation }
        return
      }
      // 首先检查是否点击了选中对象的控制点
      let controlPoint = null
      let targetObject = null
      
      // 遍历所有选中的对象，检查控制点
      for (const selectedObject of canvasService.selectedObjects.value) {
        controlPoint = canvasService.getControlPointAtPoint(worldPos.x, worldPos.y, selectedObject)
        if (controlPoint) {
          targetObject = selectedObject
          break
        }
      }
      
      if (controlPoint && targetObject) {
        if (controlPoint === 'rotation') {
          // 点击旋转控制点：开始旋转
          isDragging.value = true
          dragType.value = 'rotation'
          rotationObject.value = targetObject
          dragStart.value = { x: worldPos.x, y: worldPos.y }

          targetObject.__history = { start: { x: targetObject.x, y: targetObject.y }, startRotation: targetObject.rotation }
          
          // 记录开始旋转时的对象角度
          rotationStartAngle.value = targetObject.rotation
          
           
        } else {
          // 点击缩放控制点：开始缩放
          isDragging.value = true
          dragType.value = 'resize'
          resizeControlPoint.value = controlPoint
          resizeObject.value = targetObject
          dragStart.value = { x: worldPos.x, y: worldPos.y }

          targetObject.__history = { start: { x: targetObject.x, y: targetObject.y }, startSize: { width: targetObject.width, height: targetObject.height } }
        }
      } else {
        // 检查是否点击了对象主体
        const object = canvasService.getObjectAtPoint(worldPos.x, worldPos.y)
        
        if (object) {
          // 点击对象主体：选择或移动对象
          canvasService.handleObjectSelection(object, event.shiftKey)
          isDragging.value = true
          dragType.value = 'object'
          dragStart.value = { x: worldPos.x, y: worldPos.y }

          object.__history = { start: { x: object.x, y: object.y } }
        } else {
          // 点击空白区域：开始选择框或视图平移
          canvasService.stores.selectionStore.deselectAll()
          
          // 左键拖拽空白区域平移视图
          isDragging.value = true
          dragType.value = 'view'
          // 记录拖拽开始时的视口位置
          dragStart.value = { 
            viewportX: canvasService.viewport.value.x,
            viewportY: canvasService.viewport.value.y,
            screenX: screenX,
            screenY: screenY
          }
        }
      }
    } else if (event.button === 1) { // 中键
      // 中键拖拽：平移视图
      isDragging.value = true
      dragType.value = 'view'
      // 记录拖拽开始时的视口位置
      dragStart.value = { 
        viewportX: canvasService.viewport.value.x,
        viewportY: canvasService.viewport.value.y,
        screenX: screenX,
        screenY: screenY
      }
    }
  }

  /**
   * 处理鼠标移动事件
   */
  const handleMouseMove = (event) => {
    const rect = canvasService.canvasRef.value.getBoundingClientRect()
    
    const screenX = event.clientX - rect.left
    const screenY = event.clientY - rect.top
    const worldPos = canvasService.screenToWorld(screenX, screenY)
    
    mousePosition.value = worldPos
    // 放置模式下，预览跟随鼠标
    if (placementStore.isPlacing) {
      placementStore.updatePosition(worldPos.x, worldPos.y)
      if (triggerRedraw) triggerRedraw()
    }
    
    if (isDragging.value) {
      if (dragType.value === 'rotation' && rotationObject.value) {
        const newRotation = canvasService.calculateObjectRotation2(
          rotationObject.value,
          dragStart.value,
          worldPos.x,
          worldPos.y,
          rotationStartAngle.value
        )
        
        
        // 更新对象旋转角度
        rotationObject.value.rotation = newRotation
        
      } else if (dragType.value === 'resize' && resizeObject.value) {
        // 缩放对象
        const deltaX = worldPos.x - dragStart.value.x
        const deltaY = worldPos.y - dragStart.value.y
        
        // 计算新的对象属性
        const newObject = canvasService.calculateObjectResize(
          resizeObject.value, 
          resizeControlPoint.value, 
          deltaX, 
          deltaY
        )
        
        // 更新对象属性
        Object.assign(resizeObject.value, newObject)
        
        // 更新拖拽起始位置
        dragStart.value = { x: worldPos.x, y: worldPos.y }
        
      } else if (dragType.value === 'object' && canvasService.selectedObjects.value.length > 0) {
        // 优化：直接计算鼠标移动的偏移量
        const deltaX = worldPos.x - dragStart.value.x
        const deltaY = worldPos.y - dragStart.value.y
        
        // 更新拖拽起始位置，实现累积移动
        dragStart.value = { x: worldPos.x, y: worldPos.y }
        
        
        canvasService.handleObjectMove(canvasService.selectedObjects.value, deltaX, deltaY)
      } else if (dragType.value === 'view') {
        // 修复：正确的视口平移逻辑
        const deltaX = screenX - dragStart.value.screenX
        const deltaY = screenY - dragStart.value.screenY
        
        // 计算新的视口位置
        const newViewportX = dragStart.value.viewportX + deltaX
        const newViewportY = dragStart.value.viewportY + deltaY
        
        // 直接设置视口位置，而不是使用增量
        canvasService.viewportStore.setViewport(
          newViewportX,
          newViewportY,
          canvasService.viewport.value.zoom,
          canvasService.viewport.value.rotation
        )
        
        // 触发重绘
        if (triggerRedraw) triggerRedraw()
      }
    } else {
      // 悬停检测
      const object = canvasService.getObjectAtPoint(worldPos.x, worldPos.y)
      canvasService.stores.selectionStore.setHoveredObject(object)
    }
  }

  /**
   * 处理鼠标释放事件
   */
  const handleMouseUp = (event) => {
    // 在结束拖拽时，针对不同类型写入历史
    if (dragType.value === 'object' && canvasService.selectedObjects.value.length > 0) {
      
      if (placementStore.isPlacing) {
        placementStore.confirmPlacement()
      } else {
          
          // 判断是否是移动对象，没有移动，坐标不会更改
          const isMoved = canvasService.selectedObjects.value.some(obj => obj.x !== obj.__history?.start.x || obj.y !== obj.__history?.start.y)
          console.log('isMoved',isMoved);
          
          if (isMoved) {
             // 记录移动后的位置信息
            const operations = canvasService.selectedObjects.value.map(obj => ({
              type: 'object_move',
              action: 'move',
              data: {
                objectId: obj.id,
                oldPosition: obj.__history?.start || null,
                newPosition: { x: obj.x, y: obj.y }
              }
            }))
            historyStore.addBatchOperation(operations, `移动对象 (${operations.length})`)
          }

         
      }


    } else if (dragType.value === 'resize' && resizeObject.value) {
      historyStore.addHistoryItem({
        type: 'object_scale',
        action: 'scale',
        data: {
          objectId: resizeObject.value.id,
          oldSize: resizeObject.value.__history?.startSize || null,
          oldPosition: resizeObject.value.__history?.start || null,
          newSize: { width: resizeObject.value.width, height: resizeObject.value.height },
          newPosition: { x: resizeObject.value.x, y: resizeObject.value.y }
        }
      })
    } else if (dragType.value === 'rotation' && rotationObject.value) {
      historyStore.addHistoryItem({
        type: 'object_rotate',
        action: 'rotate',
        data: {
          objectId: rotationObject.value.id,
          oldRotation: rotationObject.value.__history?.startRotation || 0,
          newRotation: rotationObject.value.rotation
        }
      })
    }
    isDragging.value = false
    dragType.value = ''
    resizeControlPoint.value = ''
    resizeObject.value = null
    rotationObject.value = null
    rotationStartAngle.value = 0
  }

  /**
   * 处理鼠标滚轮事件
   * 职责：缩放视图
   */
  const handleWheel = (event) => {
    event.preventDefault()
    
    const rect = canvasService.canvasRef.value.getBoundingClientRect()
    const x = event.clientX - rect.left
    const y = event.clientY - rect.top
    
    const delta = event.deltaY > 0 ? 0.9 : 1.1
    const newZoom = canvasService.viewport.value.zoom * delta
    canvasService.handleViewZoom(newZoom, x, y)
  }

  /**
   * 处理右键菜单事件
   */
  const handleContextMenu = (event) => {
    event.preventDefault()
    // 放置模式下，右键取消放置
    if (placementStore.isPlacing) {
      placementStore.cancelPlacement()
      return
    }
    // 右键菜单处理 - 委托给应用层
  }

  // ==================== 键盘快捷键处理 ====================
  /**
   * 处理键盘事件
   */
  const handleKeyDown = (event) => {
    console.log('触发键盘事件',event);
    // ESC：取消放置
    if (event.code === 'Escape') {

      if (placementStore.isPlacing) {
        placementStore.cancelPlacement()
        return
      }
    }
    // 空格键：临时切换到平移工具
    if (event.code === 'Space' && !event.repeat) {
      // 可以在这里实现临时工具切换
    }
    
    // Delete键：删除选中对象
    if (event.code === 'Delete' || event.code === 'Backspace') {
      // 删除选中的对象
      if (canvasService.selectedObjects.value.length > 0) {
        // 委托给应用层处理删除逻辑
        console.log('删除选中对象')
      }
    }
    
    // 方向键：微调对象位置
    if (event.code.startsWith('Arrow')) {
      const step = event.shiftKey ? 10 : 1
      let deltaX = 0, deltaY = 0
      
      switch (event.code) {
        case 'ArrowLeft':
          deltaX = -step
          break
        case 'ArrowRight':
          deltaX = step
          break
        case 'ArrowUp':
          deltaY = -step
          break
        case 'ArrowDown':
          deltaY = step
          break
      }
      
      if (deltaX !== 0 || deltaY !== 0) {
        canvasService.handleObjectMove(canvasService.selectedObjects.value, deltaX, deltaY)
      }
    }
  }

  /**
   * 处理键盘释放事件
   */
  const handleKeyUp = (event) => {
    // 空格键释放：恢复原工具
    if (event.code === 'Space') {
      // 恢复原工具
    }
  }

  // ==================== 工具切换处理 ====================
     /**
    * 切换到选择工具
    */
   const switchToSelectTool = () => {
     canvasService.stores.toolStore.setCurrentTool('select')
   }
 
   /**
    * 切换到移动工具
    */
   const switchToMoveTool = () => {
     canvasService.stores.toolStore.setCurrentTool('move')
   }
 
   /**
    * 切换到绘制工具
    */
   const switchToDrawTool = (toolType) => {
     canvasService.stores.toolStore.setCurrentTool(toolType)
   }

  // ==================== 导出接口 ====================
  return {
    // 状态
    mousePosition,
    isDragging,
    dragType,
    
    // 鼠标事件处理
    handleMouseDown,
    handleMouseMove,
    handleMouseUp,
    handleWheel,
    handleContextMenu,
    
    // 键盘事件处理
    handleKeyDown,
    handleKeyUp,
    
    // 工具切换
    switchToSelectTool,
    switchToMoveTool,
    switchToDrawTool
  }
}
